package com.example.demo1.controller.rest;

import com.example.demo1.common.ResponseCode;
import com.example.demo1.common.ServerResponse;
import com.example.demo1.entity.BaUser;
import com.example.demo1.service.impl.service.UserService;
import com.example.demo1.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/api/login")
public class LoginRestController {

    @Autowired
    private UserService userService;

    @PostMapping(value = "/doLogin")
    private ServerResponse<String> doLogin(String userName, String password) {
        return userService.doLogin(userName, password);
    }
    
    //    @PostMapping(value = "/doLogOut")
    private ServerResponse doLogOut(HttpServletRequest request) {
        Integer userId;
        try {
            userId = Integer.parseInt(JwtUtil.dececodeToken(request.getHeader("Authorization")).get("userId") + "");
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "token已过期，请重新登录");
        }
        return userService.doLogOut(userId);
    }



    @PostMapping(value = "/getUserInfo")
    private ServerResponse<BaUser> getUserInfo(HttpServletRequest request) {
        Integer userId;
        try {
            userId = Integer.parseInt(JwtUtil.dececodeToken(request.getHeader("Authorization")).get("userId") + "");
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "token已过期，请重新登录");
        }
        return userService.getUserInfo(userId);
    }

}
